package top.linuyx.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @Author Linuyx
 * @Description 从工厂中获取bean对象
 * @Date Created in 2021-04-08 21:30
 */

@Component
public class ApplicationContextUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtils.applicationContext = applicationContext;
    }

    /**
     * 根据名称获取bean对象
     *
     * @param beanName 名称
     * @return bean对象
     */
    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    /**
     * 根据class获取bean对象
     *
     * @param aClass class
     * @param <T> 泛型
     * @return bean对象
     */
    public static<T> T getBean(Class<T> aClass){
        return applicationContext.getBean(aClass);
    }
}
